package com.qd.panda.service.plate;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.plate.PlateDTO;
import com.qd.common.panda.domain.enums.CarTypeEnum;
import com.qd.panda.etc.EtcService;
import com.qd.panda.etc.dto.constant.VehicleColorConstant;
import com.qd.panda.etc.dto.req.BaseReqDTO;
import com.qd.panda.etc.dto.req.CancelReqDTO;
import com.qd.panda.etc.dto.req.ValidateReqDTO;
import com.qd.panda.etc.dto.resp.ApplyResponseDTO;
import com.qd.panda.etc.dto.resp.SearchResponseDTO;
import com.qd.panda.etc.dto.resp.ValidateResponseDTO;
import com.qd.panda.mapper.plate.PlateMapper;
import com.qd.panda.model.Plate;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 车牌管理
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class PlateService extends BaseService<PlateMapper, Plate> {

    private static final String PREFIX_ID = "panda_plate_plateNumber_{0}";

    private final RedisTemplateUtil<Plate> redisTemplateUtil;

    private final EtcService etcService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PlateDTO save(PlateDTO dto) {
        final Plate model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PlateDTO update(PlateDTO dto) {
        final Plate historyModel = Optional.ofNullable(getById(dto.getPlateNumber())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final Plate model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param plateNumber 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String plateNumber) {
        final Plate model = Optional.ofNullable(getById(plateNumber)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(plateNumber)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(PlateDTO dto) {
        final QueryWrapper<Plate> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param plateNumber 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String plateNumber) {
        boolean exists = false;
        if (StringUtils.hasLength(plateNumber)) {
            final Plate model = getById(plateNumber);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param plateNumber 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Plate getById(String plateNumber) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, plateNumber);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(plateNumber), Plate.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param plateNumber 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PlateDTO getByIdDto(String plateNumber) {
        return Optional.ofNullable(getById(plateNumber)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public Plate getOne(PlateDTO dto) {
        final QueryWrapper<Plate> queryWrapper = createQueryWrapper(dto);
        Plate model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PlateDTO getOneDto(PlateDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<Plate> getList(PlateDTO dto) {
        final QueryWrapper<Plate> queryWrapper = createQueryWrapper(dto);
        final List<Plate> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<PlateDTO> getListDto(PlateDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(Plate model) {
        if (null == model) {
            return;
        }
        String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPlateNumber());
        redisTemplateUtil.deleteByKey(key);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public PlateDTO modelToDto(Plate model) {
        if (null == model) {
            return null;
        }
        final PlateDTO dto = new PlateDTO();
        dto.setPlateNumber(model.getPlateNumber());
        dto.setCarType(model.getCarType());
        dto.setEtcPay(model.getEtcPay());
        dto.setVehicleColor(model.getVehicleColor());
        dto.setEtcCardId(model.getEtcCardId());
        dto.setAddTime(model.getAddTime());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public Plate dtoToModel(PlateDTO dto) {
        if (null == dto) {
            return null;
        }
        final Plate model = new Plate();
        model.setPlateNumber(dto.getPlateNumber());
        model.setCarType(dto.getCarType());
        model.setEtcPay(dto.getEtcPay());
        model.setVehicleColor(dto.getVehicleColor());
        model.setEtcCardId(dto.getEtcCardId());
        model.setAddTime(dto.getAddTime());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(PlateDTO dto) {
        dto.setCarTypeDisplay(CarTypeEnum.idToDisplay(dto.getCarType()));
        dto.setEtcPayDisplay(MbUtil.idToDisplay(dto.getEtcPay()));
        dto.setVehicleColorDisplay(VehicleColorConstant.idToDisplay(dto.getVehicleColor()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<PlateDTO> modelToDtoList(List<Plate> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<Plate> dtoToModelList(List<PlateDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<Plate> createQueryWrapper(PlateDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<Plate> createQueryWrapper(PlateDTO dto, String tableAlias) {
        final QueryWrapper<Plate> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias)) {
                if (tableAlias.charAt(tableAlias.length() - 1) != '.') {
                    tableAlias += ".";
                }
            }
            if (null != dto.getCarType()) {
                queryWrapper.eq(tableAlias + "car_type", dto.getCarType());
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + "plate_number", dto.getPlateNumber());
            }
        }
        queryWrapper.orderByAsc(tableAlias + "car_type");
        queryWrapper.orderByAsc(tableAlias + "plate_number");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     */
    public List<Plate> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<Plate> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(Plate::getPlateNumber).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    /**
     * 当前车牌号是否支持ETC支付
     *
     * @param plateNumber 车牌号
     * @return sf0否 sf1是
     */
    @Transactional(readOnly = true)
    public String etcPay(String plateNumber) {
        final Plate plate = getById(plateNumber);
        if (null == plate) {
            return ConstantDto.SF0;
        }
        return StringUtils.hasText(plate.getEtcPay()) ? plate.getEtcPay() : ConstantDto.SF0;
    }

    /**
     * 当前车牌号是否支持ETC支付
     *
     * @param plateNumber  车牌号
     * @param vehicleColor 车牌颜色
     * @return sf0否 sf1是
     */
    @Transactional(rollbackFor = Exception.class)
    public PlateDTO isOpenEtc(String plateNumber, Integer vehicleColor) {
        final PlateDTO plate = Optional.ofNullable(getByIdDto(plateNumber)).orElseThrow(() -> new ApiException("车牌号不存在"));
        if (null == vehicleColor) {
            vehicleColor = plate.getVehicleColor();
        }
        if (null == vehicleColor) {
            throw new ApiException(ApiResultWrapper.NULL_ERROR, "车牌颜色不能为空");
        }
        VehicleColorConstant.checkCode(vehicleColor);
        final BaseReqDTO baseReqDTO = new BaseReqDTO().setVehiclePlate(plateNumber).setVehicleColor(vehicleColor);
        String etcPay;
        String etcCardId = null;
        SearchResponseDTO search = etcService.search(baseReqDTO);
        if (null == search) {
            etcPay = ConstantDto.SF0;
        } else {
            etcPay = search.isAuth() ? ConstantDto.SF1 : ConstantDto.SF0;
            if (search.isAuth()) {
                etcCardId = search.getCardId();
            }
        }
        baseReqDTO.freeData();
        update(plate, vehicleColor, etcPay, etcCardId);
        buildDisplay(plate);
        return plate;
    }

    /**
     * 请求开通ETC授权
     *
     * @param plateNumber  车牌号
     * @param vehicleColor 车牌颜色
     */
    @Transactional(readOnly = true)
    public ApplyResponseDTO openEtc(String plateNumber, Integer vehicleColor) {
        if (Boolean.FALSE.equals(isExistsById(plateNumber))) {
            throw new ApiException("车牌号不存在");
        }
        final BaseReqDTO baseReqDTO = new BaseReqDTO().setVehiclePlate(plateNumber).setVehicleColor(vehicleColor);
        return etcService.apply(baseReqDTO);
    }

    /**
     * 验证开通ETC授权
     *
     * @param plateNumber   车牌号
     * @param vehicleColor  车牌颜色
     * @param transactionId 请求授权流水号
     * @param authCode      验证码
     * @param etcCardId     ETC卡号
     * @return sf0失败 sf1成功
     */
    @Transactional(rollbackFor = Exception.class)
    public String validateEtc(String plateNumber, Integer vehicleColor, String transactionId, String authCode, String etcCardId) {
        final PlateDTO plate = Optional.ofNullable(getByIdDto(plateNumber)).orElseThrow(() -> new ApiException("车牌号不存在"));
        ValidateReqDTO validateReqDTO = new ValidateReqDTO();
        validateReqDTO.setAuthCode(authCode)
                .setTransactionId(transactionId)
                .setVehiclePlate(plateNumber)
                .setVehicleColor(vehicleColor);
        final ValidateResponseDTO validateResponseDTO = etcService.validate(validateReqDTO);
        validateReqDTO.freeData();
        if (!validateResponseDTO.isValidate()) {
            throw new ApiException("验证失败");
        }
        String etcPay = validateResponseDTO.isAuth() ? ConstantDto.SF1 : ConstantDto.SF0;
        update(plate, vehicleColor, etcPay, etcCardId);
        plate.freeData();
        return etcPay;
    }

    /**
     * 取消ETC授权
     *
     * @param plateNumber  车牌号
     * @param vehicleColor 车牌颜色
     * @param reason       取消原因
     * @return transactionId 取消授权流水号
     */
    @Transactional(rollbackFor = Exception.class)
    public ApplyResponseDTO closeEtc(String plateNumber, Integer vehicleColor, String reason) {
        if (Boolean.FALSE.equals(isExistsById(plateNumber))) {
            throw new ApiException("车牌号不存在");
        }
        final CancelReqDTO cancelReqDTO = new CancelReqDTO();
        reason = Base64.encode(reason);
        cancelReqDTO.setReason(reason).setVehiclePlate(plateNumber).setVehicleColor(vehicleColor);
        final ApplyResponseDTO applyResponseDTO = etcService.cancel(cancelReqDTO);
        cancelReqDTO.freeData();
        return applyResponseDTO;
    }

    /**
     * 验证取消ETC授权
     *
     * @param plateNumber   车牌号
     * @param vehicleColor  车牌颜色
     * @param transactionId 取消授权流水号
     * @param authCode      验证码
     * @param etcCardId     ETC卡号
     */
    @Transactional(rollbackFor = Exception.class)
    public void validateCancelEtc(String plateNumber, int vehicleColor, String transactionId, String authCode, String etcCardId) {
        final PlateDTO plate = Optional.ofNullable(getByIdDto(plateNumber)).orElseThrow(() -> new ApiException("车牌号不存在"));
        ValidateReqDTO validateReqDTO = new ValidateReqDTO();
        validateReqDTO.setAuthCode(authCode)
                .setTransactionId(transactionId)
                .setVehiclePlate(plateNumber)
                .setVehicleColor(vehicleColor);
        final ValidateResponseDTO validateResponseDTO = etcService.validateCancel(validateReqDTO);
        validateReqDTO.freeData();
        if (!validateResponseDTO.isValidate()) {
            throw new ApiException("验证失败");
        }
        update(plate, vehicleColor, ConstantDto.SF0, etcCardId);
        plate.freeData();
    }

    private void update(PlateDTO plate, Integer vehicleColor, String etcPay, String etcCardId) {
        boolean isUpdate = false;
        if (null != vehicleColor) {
            if (StringUtils.hasLength(plate.getEtcPay())) {
                if (!plate.getEtcPay().equals(etcPay)) {
                    plate.setEtcPay(etcPay);
                    isUpdate = true;
                }
            } else {
                plate.setEtcPay(etcPay);
                isUpdate = true;
            }
        }
        if (StringUtils.hasLength(etcPay)) {
            if (null == plate.getVehicleColor()) {
                plate.setVehicleColor(vehicleColor);
                isUpdate = true;
            } else {
                if (!plate.getVehicleColor().equals(vehicleColor)) {
                    plate.setVehicleColor(vehicleColor);
                    isUpdate = true;
                }
            }
        }
        if (StringUtils.hasLength(etcCardId)) {
            if (StringUtils.hasLength(plate.getEtcCardId())) {
                if (!plate.getEtcCardId().equals(etcCardId)) {
                    plate.setEtcCardId(etcCardId);
                    isUpdate = true;
                }
            } else {
                plate.setEtcCardId(etcCardId);
                isUpdate = true;
            }
        }
        if (isUpdate) {
            update(plate);
        }
    }
}